package com.powerhua.core.base.dao;

import com.powerhua.core.base.BaseModelCacheManager;
import com.powerhua.core.base.bean.IField;
import com.powerhua.core.base.bean.IModel;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Brian.Xie
 */
public class DeleteDao extends CommonDao {

    private static final Log LOG = LogFactory.getLog(DeleteDao.class);

    /**
     *
     * @param map
     * @param baseModelId
     * @return
     */
    public String delete(Map map, String baseModelId) {

        IModel model = BaseModelCacheManager.getInstance().getModel(baseModelId);
        if (model == null) {
            LOG.error("No model found");
            return "";
        }

        IField pkField = model.getPk();
        if (pkField == null) {
            LOG.error("No primary key found");
            return "";
        }

        Map<String, IField> fields = model.getFields();
        if (fields == null || fields.size() == 0) {
            LOG.error("No table field found");
            return "";
        }

        // 定义SQL语句存放
        StringBuffer sql = new StringBuffer();
        sql.append("delete " + model.getModelTable() + " where ");

        // 主键
        String pkColumn = model.getPk().getName().toLowerCase();
        if (map.get(pkColumn) == null) {
            LOG.error("No primary key found in request, can not delete");
            return "";
        } else {
            String[] pkValues = (String[]) map.get(pkColumn);
            for (int j = 0; j < pkValues.length; j++) {
                if (j == 0) {
                    sql.append(pkColumn);
                    sql.append("=?");
                } else {
                    sql.append(" or ");
                    sql.append(pkColumn);
                    sql.append("=?");
                }
            }
        }

        if (map.get(pkColumn) == null) {
            LOG.error("Can not find table primary key in request");
            return "";
        } else {
            String[] pkValues = (String[]) map.get(pkColumn);
            jdbcTemplate.update(sql.toString(), pkValues);
        }

        return "";
    }
}
